package com.iflytek.iot.hadoop.dfs.service;

import com.iflytek.iot.hadoop.dfs.config.HdfsProperties;
import com.iflytek.iot.hadoop.dfs.util.HdfsUtil;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author yu 2019/11/28.
 */
public class FileHdfsService implements HdfsService {


    private static final Logger LOGGER = LoggerFactory.getLogger(FileHdfsService.class);

    /**
     * hdfs config
     */
    private Configuration configuration;

    /**
     * 自动义配置
     */
    private HdfsProperties hdfsProperties;


    @Override
    public void setConfiguration(Configuration configuration) {
        this.configuration = configuration;
    }

    @Override
    public void setHdfsProperties(HdfsProperties hdfsProperties) {
        this.hdfsProperties = hdfsProperties;
    }

    @Override
    public boolean delete(String fileName) {
        FileSystem fileSystem = this.createFileSystem();
        return HdfsUtil.delete(fileName, fileSystem);
    }

    @Override
    public boolean createDir(String hdfsDir) {
        FileSystem fileSystem = this.createFileSystem();
        return HdfsUtil.createDir(hdfsDir, fileSystem);
    }

    @Override
    public List<String> listFile(String path) {
        FileSystem fileSystem = this.createFileSystem();
        List<String> files;
        try {
            files = HdfsUtil.getFileList(path, fileSystem);
        } catch (IOException e) {
            LOGGER.error("获取失败");
            files = new ArrayList<>(0);
        }
        return files;
    }

    @Override
    public String download(String remoteFile) {
        FileSystem fileSystem = this.createFileSystem();
        try {
            return HdfsUtil.download(remoteFile, fileSystem);
        } catch (IOException e) {
            LOGGER.error("从Hdfs文件系统下载文件失败", e);
            return null;
        }
    }

    @Override
    public String createFile(String filePath, String contents) {
        FileSystem fileSystem = this.createFileSystem();
        try {
            return HdfsUtil.createFile(filePath, contents, fileSystem);
        } catch (IOException e) {
            LOGGER.error("创建文件失败", e);
            return null;
        }
    }

    @Override
    public boolean createFileAppendable(String filePath, String contents) {
        FileSystem fileSystem = this.createFileSystem();
        try {
            HdfsUtil.createFileAppendable(filePath, contents, fileSystem);
            return true;
        } catch (IOException e) {
            LOGGER.error("创建文件失败", e);
        }
        return false;
    }

    /**
     * 创建hdfs文件系统
     *
     * @return
     */
    private FileSystem createFileSystem() {
        return HdfsUtil.getFileSystem(this.configuration, this.hdfsProperties.getServerUrl(), this.hdfsProperties.getUser());
    }
}
